<template>
    <el-select v-model="sval" :class="className" :popper-class="popperClass" clearable :placeholder="placeholder||'请选择'" :style="{width}" @change="onChcange" class="small-el-input__inner" popper-class="samll-el-select-dropdown__list" :multiple="multiple">
        <el-option v-for="dt in lists" :key="dt.code" :value="dt.code" :label="dt.meaning" />
    </el-select>
</template>
<script setup>
import {ref,onMounted,watch,nextTick} from "vue"
import {getDropdownList} from '@/api/plant'
import { useUserStore } from '@/pinia/modules/user'

const userStore = useUserStore()

const props = defineProps({
    modelValue:'',
    lovCode:'',
    param2:'',
    width:{
        type:String,
        default:'100%'
    },
    params:{  // 查询条件
        type:Object,
        default:{}
    }, 
    multiple:{ // 多选
        type:Boolean,
        default:false
    },
    optLists:'',
    placeholder:'',
    className:'',
    popperClass:"",
    keyName:'' // 返回的属性名对应的值
})
const emit = defineEmits(['update:modelValue','change'])
const sval = ref('')
const lists = ref('')

onMounted(()=>{ 
    if(props.optLists){
        lists.value = props.optLists
        sval.value = props.modelValue || '' // 设置默认选项
    }else{
        getTableData()
    }  
})

watch(()=>props.modelValue,(n,o)=>{
    sval.value = n
})

const getTableData = async () => {
  const res = await getDropdownList({ 
    page: 1, 
    limit: 1000000,
    lovCode:props.lovCode,
    param2:props.param2
  })
  if (res.code == 0) {
    lists.value = res.data
    //console.log("GGGGG:",props)
    sval.value = props.modelValue || '' // 设置默认选项
  }
}

const onChcange = ()=>{

    if(props.keyName){
        const item = lists.value.find(ele =>ele.code == sval.value)
        emit('update:modelValue',item[props.keyName]) 
    }else{
        emit('update:modelValue',sval.value) 
    } 
    if(props.multiple){ // 多选
        let slObjArr=[] // 选择的对象数据
        sval.value.forEach(item => {
            const uit = lists.value.find(ele => ele.code == item)
            slObjArr.push(uit)
        });
        emit('change',slObjArr) 
    }else{ // 单选
        emit('change',lists.value.find(ele =>ele.code == sval.value)) 
    }
    
}

</script>

<style scoped lang="scss">
</style>